import logging

import webapp2
from google.appengine.api import users
from util.webapp import ShopkeepApplication, ShopkeepHandler
from models.Item import Item
from models.User import User
from models.Rating import Rating

class RatingsPage(ShopkeepHandler):
	def get(self):
		user = users.get_current_user()
		if isinstance(self.target, Item) and not self.target.canView(user):
			self.abort(403)

		self.render_response('ratings.html', {
			'title': self.target.title if isinstance(self.target, Item) else self.target.getName(),
			'target': self.target,
			'ratings': Rating.getRatings(self.target).run()
		})

	def post(self):
		if self.request.POST.get('action') == 'delete':
			logging.info('User deleted rating.', extra={'target': self.target})
			self.delete()
		else:
			logging.info('User added rating.', extra={'target': self.target})
			self.put(self.request.POST)
		self.get()

	def put(self, data=None):
		if data is None:
			data = urlparse.parse_qs(
				self.request.body,
				keep_blank_values=True,
				strict_parsing=True
			)

		user = users.get_current_user()
		if isinstance(self.target, Item) and not self.target.canView(user):
			self.abort(403)

		self.rating.rating = int(data.get('rating'))
		self.rating.comments = data.get('comments')
		self.rating.put()

	def delete(self):
		self.rating.delete()

	@webapp2.cached_property
	def rating(self):
		user = users.get_current_user()
		ratings = Rating.getRatings(self.target)
		ratings.filter('rater =', user)

		rating = ratings.get()
		if rating is None:
			if isinstance(self.target, Item):
				rating = Rating(
					rater=user,
					seller=self.target.seller,
					item=self.target,
					rating=0
				)
			else:
				rating = Rating(
					rater=user,
					seller=self.target.id,
					rating=0
				)
		return rating

	@webapp2.cached_property
	def target(self):
		info = self.request.path.split('/')

		assert info[0] == ''
		if len(info) == 4:
			assert info[3] == 'ratings'
			user_id = int(info[2])
			obj = User.get_by_id(user_id)
		elif len(info) == 6:
			assert info[5] == 'ratings'
			item_id = int(info[4])
			obj = Item.get_by_id(item_id)
		else:
			self.abort(404)

		if obj is None:
			self.abort(404)
			# Should not be reached, since self.abort throws excpt

		return obj


app = ShopkeepApplication([
	('/users/.+/ratings', RatingsPage),
	('/users/.+/items/.+/ratings', RatingsPage)
])
